<template>
  <div class="delivery-management">
    <!-- 顶部搜索和筛选 -->
    <div class="action-bar">
      <div class="search-box">
        <input 
          type="text" 
          v-model="searchQuery" 
          placeholder="搜索订单号/收件人"
          @input="handleSearch"
        >
        <i class="fas fa-search"></i>
      </div>
      <div class="filters">
        <select v-model="statusFilter">
          <option value="">全部状态</option>
          <option value="pending">待发货</option>
          <option value="shipping">配送中</option>
          <option value="delivered">已送达</option>
          <option value="returned">已退回</option>
        </select>
        <div class="date-range">
          <input 
            type="date" 
            v-model="dateRange.start"
            :max="dateRange.end"
          >
          <span>至</span>
          <input 
            type="date" 
            v-model="dateRange.end"
            :min="dateRange.start"
          >
        </div>
      </div>
      <button class="export-btn" @click="exportDelivery">
        <i class="fas fa-download"></i>
        导出配送单
      </button>
    </div>

    <!-- 配送列表 -->
    <div class="delivery-table">
      <table>
        <thead>
          <tr>
            <th>订单号</th>
            <th>收件信息</th>
            <th>物流信息</th>
            <th>配送状态</th>
            <th>发货时间</th>
            <th>预计送达</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="delivery in filteredDeliveries" :key="delivery._id">
            <td>{{ delivery.orderId }}</td>
            <td>
              <div class="receiver-info">
                <div>{{ delivery.receiver.name }}</div>
                <div class="text-small">{{ delivery.receiver.phone }}</div>
                <div class="text-small">{{ delivery.receiver.address }}</div>
              </div>
            </td>
            <td>
              <div class="logistics-info">
                <div>{{ getCarrierName(delivery.carrier) }}</div>
                <div class="text-small">{{ delivery.trackingNumber }}</div>
              </div>
            </td>
            <td>
              <span class="status-tag" :class="delivery.status">
                {{ getStatusText(delivery.status) }}
              </span>
            </td>
            <td>{{ formatDate(delivery.shippedAt) }}</td>
            <td>{{ formatDate(delivery.estimatedDeliveryAt) }}</td>
            <td>
              <div class="action-buttons">
                <button 
                  class="track-btn" 
                  @click="trackDelivery(delivery)"
                  title="跟踪物流"
                >
                  <i class="fas fa-map-marker-alt"></i>
                </button>
                <button 
                  v-if="delivery.status === 'shipping'"
                  class="complete-btn" 
                  @click="markAsDelivered(delivery)"
                  title="标记送达"
                >
                  <i class="fas fa-check"></i>
                </button>
                <button 
                  v-if="delivery.status === 'shipping'"
                  class="return-btn" 
                  @click="markAsReturned(delivery)"
                  title="标记退回"
                >
                  <i class="fas fa-undo"></i>
                </button>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 分页 -->
    <div class="pagination">
      <button 
        :disabled="currentPage === 1"
        @click="currentPage--"
      >
        <i class="fas fa-chevron-left"></i>
      </button>
      <span>第 {{ currentPage }} 页</span>
      <button 
        :disabled="currentPage === totalPages"
        @click="currentPage++"
      >
        <i class="fas fa-chevron-right"></i>
      </button>
    </div>

    <!-- 物流跟踪弹窗 -->
    <div class="modal" v-if="showTrackingModal">
      <div class="modal-content">
        <div class="modal-header">
          <h3>物流跟踪</h3>
          <button class="close-btn" @click="showTrackingModal = false">
            <i class="fas fa-times"></i>
          </button>
        </div>
        <div class="modal-body">
          <div class="tracking-info" v-if="selectedDelivery">
            <div class="delivery-header">
              <div class="carrier-info">
                <span class="carrier">{{ getCarrierName(selectedDelivery.carrier) }}</span>
                <span class="tracking-number">运单号：{{ selectedDelivery.trackingNumber }}</span>
              </div>
              <div class="delivery-status">
                <span class="status-tag" :class="selectedDelivery.status">
                  {{ getStatusText(selectedDelivery.status) }}
                </span>
              </div>
            </div>

            <div class="tracking-timeline">
              <div 
                v-for="(track, index) in trackingRecords" 
                :key="index"
                class="timeline-item"
                :class="{ active: index === 0 }"
              >
                <div class="timeline-point"></div>
                <div class="timeline-content">
                  <div class="track-time">{{ formatDate(track.time) }}</div>
                  <div class="track-info">{{ track.info }}</div>
                  <div class="track-location">{{ track.location }}</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { deliveryApi } from '@/api'

// 状态变量
const deliveries = ref([])
const searchQuery = ref('')
const statusFilter = ref('')
const currentPage = ref(1)
const totalPages = ref(1)
const showTrackingModal = ref(false)
const selectedDelivery = ref(null)
const trackingRecords = ref([])
const dateRange = ref({
  start: '',
  end: new Date().toISOString().split('T')[0]
})

// 获取物流公司名称
const getCarrierName = (code: string) => {
  const carriers = {
    sf: '顺丰速运',
    zt: '中通快递',
    yd: '韵达快递',
    ems: 'EMS'
  }
  return carriers[code as keyof typeof carriers] || code
}

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap = {
    pending: '待发货',
    shipping: '配送中',
    delivered: '已送达',
    returned: '已退回'
  }
  return statusMap[status as keyof typeof statusMap] || status
}

// 格式化日期
const formatDate = (date: string) => {
  if (!date) return '-'
  return new Date(date).toLocaleString('zh-CN')
}

// 过滤配送列表
const filteredDeliveries = computed(() => {
  return deliveries.value.filter(delivery => {
    const matchQuery = delivery.orderId.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
                      delivery.receiver.name.toLowerCase().includes(searchQuery.value.toLowerCase())
    const matchStatus = !statusFilter.value || delivery.status === statusFilter.value
    const deliveryDate = new Date(delivery.shippedAt)
    const matchDate = (!dateRange.value.start || deliveryDate >= new Date(dateRange.value.start)) &&
                     (!dateRange.value.end || deliveryDate <= new Date(dateRange.value.end))
    return matchQuery && matchStatus && matchDate
  })
})

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  fetchDeliveries()
}

// 跟踪物流
const trackDelivery = async (delivery: any) => {
  selectedDelivery.value = delivery
  showTrackingModal.value = true
  
  try {
    // 模拟获取物流跟踪记录
    trackingRecords.value = [
      {
        time: new Date().toISOString(),
        info: '快件已签收，签收人：本人',
        location: '广州市天河区'
      },
      {
        time: new Date(Date.now() - 2 * 60 * 60 * 1000).toISOString(),
        info: '快件正在派送中',
        location: '广州市天河区派送点'
      },
      {
        time: new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString(),
        info: '快件已到达',
        location: '广州转运中心'
      }
    ]
  } catch (error) {
    console.error('Failed to fetch tracking records:', error)
  }
}

// 标记为已送达
const markAsDelivered = async (delivery: any) => {
  try {
    await deliveryApi.updateStatus(delivery._id, 'delivered')
    const index = deliveries.value.findIndex(d => d._id === delivery._id)
    if (index !== -1) {
      deliveries.value[index].status = 'delivered'
    }
  } catch (error) {
    console.error('Failed to mark as delivered:', error)
  }
}

// 标记为已退回
const markAsReturned = async (delivery: any) => {
  if (!confirm('确定要将此订单标记为已退回吗？')) return

  try {
    await deliveryApi.updateStatus(delivery._id, 'returned')
    const index = deliveries.value.findIndex(d => d._id === delivery._id)
    if (index !== -1) {
      deliveries.value[index].status = 'returned'
    }
  } catch (error) {
    console.error('Failed to mark as returned:', error)
  }
}

// 导出配送单
const exportDelivery = () => {
  // 实现导出逻辑
}

// 获取配送列表
const fetchDeliveries = async () => {
  try {
    const response = await deliveryApi.getList({
      page: currentPage.value,
      status: statusFilter.value,
      startDate: dateRange.value.start,
      endDate: dateRange.value.end
    })
    deliveries.value = response.data
    totalPages.value = Math.ceil(response.total / response.pageSize)
  } catch (error) {
    console.error('Failed to fetch deliveries:', error)
  }
}

// 初始化
fetchDeliveries()
</script>

<style scoped>
.delivery-management {
  padding: 24px;
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.search-box {
  position: relative;
  width: 300px;
}

.search-box input {
  width: 100%;
  padding: 8px 32px 8px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
}

.search-box i {
  position: absolute;
  right: 12px;
  top: 50%;
  transform: translateY(-50%);
  color: #999;
}

.filters {
  display: flex;
  gap: 16px;
  align-items: center;
}

.filters select {
  padding: 8px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
}

.date-range {
  display: flex;
  align-items: center;
  gap: 8px;
}

.date-range input {
  padding: 8px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
}

.export-btn {
  padding: 8px 16px;
  background-color: #52c41a;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8px;
}

.delivery-table {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.06);
}

table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #f0f0f0;
}

th {
  background: #fafafa;
  font-weight: 500;
  color: #666;
}

.receiver-info,
.logistics-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.text-small {
  font-size: 12px;
  color: #999;
}

.status-tag {
  padding: 2px 8px;
  border-radius: 10px;
  font-size: 12px;
}

.status-tag.pending {
  background: #fff7e6;
  color: #faad14;
}

.status-tag.shipping {
  background: #e6f7ff;
  color: #1890ff;
}

.status-tag.delivered {
  background: #f6ffed;
  color: #52c41a;
}

.status-tag.returned {
  background: #fff1f0;
  color: #ff4d4f;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.action-buttons button {
  padding: 4px 8px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.track-btn {
  background: #e6f7ff;
  color: #1890ff;
}

.complete-btn {
  background: #f6ffed;
  color: #52c41a;
}

.return-btn {
  background: #fff1f0;
  color: #ff4d4f;
}

.pagination {
  margin-top: 24px;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 16px;
}

.pagination button {
  padding: 4px 8px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  background: white;
  cursor: pointer;
}

.pagination button:disabled {
  background: #f5f5f5;
  cursor: not-allowed;
}

.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 8px;
  width: 600px;
  max-width: 90%;
  max-height: 90vh;
  overflow-y: auto;
}

.modal-header {
  padding: 16px 24px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h3 {
  margin: 0;
}

.close-btn {
  border: none;
  background: none;
  font-size: 18px;
  cursor: pointer;
  color: #999;
}

.modal-body {
  padding: 24px;
}

.tracking-info {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.delivery-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.carrier-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.carrier {
  font-size: 16px;
  font-weight: bold;
}

.tracking-number {
  font-size: 12px;
  color: #666;
}

.tracking-timeline {
  display: flex;
  flex-direction: column;
  gap: 24px;
  padding-left: 16px;
}

.timeline-item {
  position: relative;
  padding-left: 24px;
}

.timeline-item::before {
  content: '';
  position: absolute;
  left: 0;
  top: 24px;
  bottom: -24px;
  width: 1px;
  background-color: #e8e8e8;
}

.timeline-item:last-child::before {
  display: none;
}

.timeline-point {
  position: absolute;
  left: -5px;
  top: 8px;
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background-color: #e8e8e8;
}

.timeline-item.active .timeline-point {
  background-color: #1890ff;
  border: 2px solid #e6f7ff;
}

.timeline-content {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.track-time {
  font-size: 14px;
  color: #999;
}

.track-info {
  font-size: 14px;
  color: #333;
}

.track-location {
  font-size: 12px;
  color: #666;
}

.timeline-item.active .track-info {
  color: #1890ff;
  font-weight: bold;
}
</style> 